import 'package:dashed_circular_progress_bar/dashed_circular_progress_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:overload_guard/app_theme.dart';
import 'package:overload_guard/pages/data_detail_detail_page.dart';
import 'package:overload_guard/pages/data_list_page.dart';
import 'package:overload_guard/services/api_service.dart';
import 'package:overload_guard/services/db_service.dart';
import 'package:overload_guard/widgets/buttons.dart';
import 'package:overload_guard/widgets/dialogs.dart';

class DataDetailPage extends StatefulWidget {
  final String templateNum;

  const DataDetailPage({super.key, required this.templateNum});

  @override
  State<DataDetailPage> createState() => _DataDetailPageState();
}

class _DataDetailPageState extends State<DataDetailPage> {
  late Future<dynamic> futureData;

  Future<dynamic> fetchData() async {
    var result = await APIService.shippingQueryDetail(
        templateNum: widget.templateNum,
        userId: await DBService.getData(DBKey.userId));

    /*Map result = {
      "carNum":"carNum",
          "templateNum":"templateNum",
          "containerNum":"containerNum",
          "updateTime":"updateTime",
      "totalWeight":100.0,
      "realTotalWeight":30.0,
      "leftRight":100.0,
      "realLeftRight":-26.0,
      "frontRear":100.0,
      "realFrontRear":-222.0
    };*/

    _valueNotifierTotal = ValueNotifier(
        (result["realTotalWeight"].abs() > result["totalWeight"]
                ? result["totalWeight"]
                : result["realTotalWeight"].abs()) /
            (result["totalWeight"] ?? 100) *
            100);

    _valueNotifierLR = ValueNotifier(
        (result["realLeftRight"].abs() > result["leftRight"]
                ? result["leftRight"]
                : result["realLeftRight"].abs()) /
            (result["leftRight"] ?? 100) *
            100);

    _valueNotifierFB = ValueNotifier(
        (result["realFrontRear"].abs() > result["frontRear"]
                ? result["frontRear"]
                : result["realFrontRear"].abs()) /
            (result["frontRear"] ?? 100) *
            100);

    print('result: ${result["frontDetailsDTO"]["history"]}');

    return result;
  }


  @override
  void initState() {
    super.initState();
    futureData = fetchData();


    _scrollController = ScrollController();
  }

  void refreshData() {
    setState(() {
      futureData = fetchData(); // 每次调用setState时重新获取数据
    });
  }



  void scrollToTop() {
    _scrollController.animateTo(
      0, // 滚动到顶部的位置
      duration: Duration(seconds: 1), // 滚动时间
      curve: Curves.easeInOut, // 滚动的曲线效果
    );
  }

  late ValueNotifier<double> _valueNotifierTotal = ValueNotifier(10);
  late ValueNotifier<double> _valueNotifierLR = ValueNotifier(20);
  late ValueNotifier<double> _valueNotifierFB = ValueNotifier(100);

  late ScrollController _scrollController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("车辆信息", style: TextStyle(color: Colors.white)),
        backgroundColor: AppTheme.primaryColor,
        centerTitle: true,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: FutureBuilder(
        future: futureData,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            print('加载完成');
            return snapshot.data.isNotEmpty
                ? SingleChildScrollView(
              controller: _scrollController,
              child: Column(
                children: [
                  infoTile("车牌号", snapshot.data["carNum"]),
                  infoTile("车板号", snapshot.data["templateNum"]),
                  infoTile("车板详细信息", "", onTap: () {
                    Get.to(DataDetailDetailPage(detailData: snapshot.data));
                  }),
                  infoTile("集装箱编号", snapshot.data["containerNum"]),
                  infoTile("检测时间", snapshot.data["updateTime"]),
                  Row(
                    children: [
                      Container(
                        padding: EdgeInsets.only(left: 10),
                        child: Row(
                          children: [
                            Column(
                              children: [
                                ...[
                                  Container(
                                    child: Row(
                                      children: [
                                        Container(
                                          width: 80,
                                          color: Color(0xFFF6C142),
                                          child: Center(
                                            child: Text("传感器编号"),
                                          ),
                                        ),
                                        Container(
                                          color: Colors.white,
                                          width: 1,
                                        ),
                                        Container(
                                          width: 80,
                                          color: Color(0xFFF6C142),
                                          child: Center(
                                            child: Text("检测结果/kg"),
                                          ),
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                                ...[1, 2, 3, 4].map((key) {
                                  return Container(
                                    child: Row(
                                      children: [
                                        Container(
                                          width: 80,
                                          color: key % 2 == 0
                                              ? Color(0xFFFBE8CE)
                                              : Color(0xFFFDF4E8),
                                          child: Center(
                                            child: Text("$key"),
                                          ),
                                        ),
                                        Container(
                                          color: Colors.white,
                                          width: 1,
                                        ),
                                        Container(
                                          width: 80,
                                          color: key % 2 == 0
                                              ? Color(0xFFFBE8CE)
                                              : Color(0xFFFDF4E8),
                                          child: Center(
                                            child: Text(
                                                "${snapshot.data["weight$key"]}"),
                                          ),
                                        ),
                                      ],
                                    ),
                                  );
                                }).toList()
                              ],
                            ),
                          ],
                        ),
                      ),
                      SizedBox(
                        width: 10,
                      ),
                      Row(
                        children: [
                          Container(
                            color: Colors.blue,
                            width: 80,
                            height: 80,
                            child: Image.asset("assets/car1.png"),
                          ),
                          Stack(
                            children: [
                              Container(
                                color: Color(0xFFEA3223),
                                width: 120,
                                height: 80,
                              ),
                              // 左上角圆点
                              Positioned(
                                top: 10,
                                left: 10,
                                child: dot(
                                    no: 2,
                                    green: snapshot.data["link1"] >= 0),
                              ),
                              // 右上角圆点
                              Positioned(
                                top: 10,
                                right: 10,
                                child: dot(
                                    no: 3,
                                    green: snapshot.data["link2"] >= 0),
                              ),
                              // 左下角圆点
                              Positioned(
                                bottom: 10,
                                left: 10,
                                child: dot(
                                    no: 1,
                                    green: snapshot.data["link3"] >= 0),
                              ),
                              // 右下角圆点
                              Positioned(
                                bottom: 10,
                                right: 10,
                                child: dot(
                                    no: 4,
                                    green: snapshot.data["link4"] >= 0),
                              ),
                            ],
                          )
                        ],
                      )
                    ],
                  ),
                  titleCol(title2: "总重量 / kg"),
                  _progress(
                      title: "${snapshot.data["realTotalWeight"]}",
                      valueNotifier: _valueNotifierTotal,
                      history: snapshot.data["totalDetailsDTO"]["history"]),
                  titleCol(title2: "左右偏载 / mm"),
                  _progress(
                      title: "${snapshot.data["realLeftRight"]}",
                      valueNotifier: _valueNotifierLR,
                      history: snapshot.data["leftDetailsDTO"]["history"]),
                  titleCol(title2: "前后偏重 / kg"),
                  _progress(
                      title: "${snapshot.data["realFrontRear"]}",
                      valueNotifier: _valueNotifierFB,
                      history: snapshot.data["frontDetailsDTO"]["history"]),
                  Padding(
                    padding: EdgeInsets.only(
                        top: 3, left: 10, right: 10, bottom: 10),
                    child: Container(
                      child: mainSubmitButton("重新检测", () async {
                        var result = await APIService.shippingTrigger(
                            templateNum: widget.templateNum);

                        refreshData();

                        scrollToTop();

                        Dialogs.showSuccess(title: "重新检测完成");
                      }, context, Colors.blue),
                    ),
                  ),
                  Padding(
                    padding:
                    EdgeInsets.only(left: 10, right: 10, bottom: 10),
                    child: mainSubmitButton("删除车板", () async {
                      Get.defaultDialog(
                          title: "警告",
                          textConfirm: "确认",
                          textCancel: "取消",
                          content: Text("确认删除？"),
                          onConfirm: () async {
                            var result = await APIService.shippingRemove(
                                id: snapshot.data["id"].toString());

                            if (result != null) {
                              Get.back(result: true, closeOverlays: true);
                              Dialogs.showSuccess(title: "删除成功！");
                            }
                          });
                    }, context, Colors.red),
                  )
                ],
              ),
            )
                : Center(
                    child: Text("暂无数据"),
                  );
          } else if (snapshot.hasError) {
            snapshot.printError();
            print('snapshot error: ${snapshot.error}');
            return Text('报错了！');
          } else {
            print('加载中');
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }

  Widget dot({required int no, required bool green}) {
    return Container(
      width: 20,
      height: 20,
      decoration: BoxDecoration(
        color: green ? Colors.green : Colors.deepOrange,
        shape: BoxShape.circle,
      ),
      child: Center(
        child: Text(
          "$no",
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }

  Widget infoTile(title, message, {Function()? onTap}) {
    return Container(
      height: 46,
      child: ListTile(
        title: Text(title),
        trailing: onTap != null
            ? Icon(Icons.keyboard_arrow_right)
            : Text(message, style: Theme.of(context).textTheme.labelLarge),
        onTap: onTap,
      ),
    );
  }

  Widget _progress(
      {required ValueNotifier<double> valueNotifier,
      required title,
      required List history}) {
    var valueAbs = valueNotifier.value.abs();
    return Container(
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
              flex: 1,
              child: Container(
                child: Column(
                  children: history
                      .map((num) => Container(
                            width: 120,
                            color: history.indexOf(num) % 2 == 0
                                ? Color(0xFFFBE8CE)
                                : Color(0xFFFDF4E8),
                            child: Center(
                              child: Text("$num"),
                            ),
                          ))
                      .toList(),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                width: 100,
                height: 100,
                child: DashedCircularProgressBar.aspectRatio(
                  aspectRatio: 1,
                  // width ÷ height
                  valueNotifier: valueNotifier,
                  progress: valueAbs,
                  startAngle: 225,
                  sweepAngle: 270,
                  foregroundColor: valueAbs == 100 ? Colors.red : Colors.green,
                  backgroundColor: const Color(0xffeeeeee),
                  foregroundStrokeWidth: 15,
                  backgroundStrokeWidth: 15,
                  animation: true,
                  seekSize: 6,
                  seekColor: const Color(0xffeeeeee),
                  child: Center(
                    child: ValueListenableBuilder(
                        valueListenable: valueNotifier,
                        builder: (_, double value, __) => Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Text(
                                  '${value.toInt().abs()}%',
                                  style: const TextStyle(
                                      color: Colors.black,
                                      fontWeight: FontWeight.w300,
                                      fontSize: 20),
                                ),
                                Center(
                                  child: Text(
                                    title,
                                    style: const TextStyle(
                                        color: Color(0xff3b3939), fontSize: 12),
                                  ),
                                ),
                              ],
                            )),
                  ),
                ),
              )),
          Expanded(
              flex: 1,
              child: Container(
                width: 100,
                height: 100,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                child: Container(
                  margin: EdgeInsets.all(25),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: valueAbs == 100 ? Colors.red : Colors.green,
                  ),
                ),
              )),
        ],
      ),
    );
  }

  Widget titleCol(
      {String title = "状态",
      required String title2,
      String title3 = "近 5 次数据"}) {
    return Padding(
      padding: EdgeInsets.only(top: 5, bottom: 5),
      child: Container(
          height: 30,
          color: AppTheme.primaryColor,
          child: Row(children: [
            Expanded(
              flex: 1,
              child: Center(
                child: Text(title3, style: TextStyle(color: Colors.white)),
              ),
            ),
            Expanded(
              flex: 1,
              child: Center(
                child: Text(title2, style: TextStyle(color: Colors.white)),
              ),
            ),
            Expanded(
              flex: 1,
              child: Center(
                child: Text(title, style: TextStyle(color: Colors.white)),
              ),
            ),
          ])),
    );
  }
}
